package com.compty.security.manager;

import java.util.Set;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.security.domain.Resc;
import com.compty.security.domain.Role;
import com.compty.security.domain.User;


public class RoleManager extends HibernateEntityDao<Role> {
	
	 private RescManager rescManager;
	 private UserManager userManager;

	public void setRescManager(RescManager rescManager) {
		this.rescManager = rescManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	/**
     * @param o role.
     */
    @Override
    public void save(Object o) {
        super.save(o);

        if (o instanceof Role) {
            flush();

            Role role = (Role) o;

            Set<Resc> rescs = role.getRescs();

            for (Resc resc : rescs) {
                saveRoleInCache(resc);
            }

            Set<User> users = role.getUsers();

            for (User user : users) {
                flushUserAuth(user);
            }
        }
    }

    /**
     * @param o role.
     */
    @Override
    public void remove(Object o) {
        super.remove(o);

        Role role = (Role) o;
        removeAuthoritiesInCache(role.getName());
    }

    /**
     * 将资源保存到缓存里.
     *
     * @param resc 资源
     */
    public void saveRoleInCache(Resc resc) {
    	if(rescManager.getResourceFromCache(resc.getResString()) == null){
    		rescManager.save(resc);
    	}
    }

    /**
     * 刷新用户权限.
     *
     * @param user User
     */
    public void flushUserAuth(User user) {
        userManager.removeUserInCache(user.getUsername());
        userManager.save(user);
    }

    /**
     * 删除缓存中的授权.
     * @param authority 授权
     */
    private void removeAuthoritiesInCache(String authority) {
    	userManager.initUserInCache();
    }
    
}
